import { Request, Response, NextFunction } from 'express'
import { checkUserInfo } from '@server/auth/check-auth'
import { UnauthorizedError } from '@server/error/errors'
import { AuthInfo } from '@/data/auth-info'
import type { AuthAssert } from '@server/types/auth-assert'

// 创建权限断言对象
function createAuthAssert(authInfo: AuthInfo): AuthAssert {
  return {
    canViewAbout() {
      if (!authInfo.canViewAbout) {
        throw new UnauthorizedError('Not authorized to view about')
      }
    },
    canGetReleaseList() {
      if (!authInfo.canGetReleaseList) {
        throw new UnauthorizedError('Not authorized to get release list')
      }
    },
    canDeleteRelease() {
      if (!authInfo.canDeleteRelease) {
        throw new UnauthorizedError('Not authorized to delete release')
      }
    },
    canUpdateRelease() {
      if (!authInfo.canUpdateRelease) {
        throw new UnauthorizedError('Not authorized to update release')
      }
    },
    canPublishRelease() {
      if (!authInfo.canPublishRelease) {
        throw new UnauthorizedError('Not authorized to publish release')
      }
    },
    canUploadPackage() {
      if (!authInfo.canUploadPackage) {
        throw new UnauthorizedError('Not authorized to upload package')
      }
    },
    canDownloadPackage() {
      if (!authInfo.canDownloadPackage) {
        throw new UnauthorizedError('Not authorized to download package')
      }
    },
    canGetPackageList() {
      if (!authInfo.canGetPackageList) {
        throw new UnauthorizedError('Not authorized to get package list')
      }
    },
    canViewClientInfo() {
      if (!authInfo.canViewClientInfo) {
        throw new UnauthorizedError('Not authorized to view client info')
      }
    },
    canSaveClientInfo() {
      if (!authInfo.canSaveClientInfo) {
        throw new UnauthorizedError('Not authorized to save client info')
      }
    },
    canManageGrayGroups() {
      if (!authInfo.canManageGrayGroups) {
        throw new UnauthorizedError('Not authorized to manage gray groups')
      }
    },
  }
}

// 鉴权中间件
export function authMiddleware(req: Request, res: Response, next: NextFunction) {
  try {
    const userInfo = checkUserInfo(req)
    req.auth = {
      ...userInfo,
      assert: createAuthAssert(userInfo.auth),
    }
    next()
  } catch (error) {
    next(error)
  }
}
